package com.cuit.qx.utils;

import cn.afterturn.easypoi.word.WordExportUtil;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Map;

/**
 * @Date 2021/11/23 14:25
 * @Description word模板生成及转化工具类
 * @Author lcj
 */
@Slf4j
@Component
public class AsposeWordsUtils {


    /**
     * 根据模板生成word
     * @param map
     * @param wordFile
     * @param productfile
     */
    public void doc1word(Map<String,Object> map, String wordFile, String productfile){
        try {
            XWPFDocument doc = WordExportUtil.exportWord07(wordFile,map);
            FileOutputStream fos = new FileOutputStream(productfile);
            doc.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断是否有授权文件 如果没有则会认为是试用版，转换的文件会有水印
     *@return
     */
    public boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = AsposeWordsUtils.class.getClassLoader().getResourceAsStream("license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Word转PDF操作
     *@param sourcerFile 源文件
     *@param targetFile 目标文件
     */
    public void doc2pdf(String sourcerFile,String targetFile) {
        if (!getLicense()) {// 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        try {
            long old = System.currentTimeMillis();
            File file = new File(targetFile);  //新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(sourcerFile);                    //sourcerFile是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            os.close();
            long now = System.currentTimeMillis();
//            log.info("转化用时{}秒",((now - old) / 1000.0));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
